package com.jd.threed.读写锁的使用;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁规则：
 *
 */
public class ReadWriteLockDemo {

    private static final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(false);

    private static final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

    private static final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    public static void read () {


        ReentrantLock lock = new ReentrantLock();
        readLock.lock();

        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();



        try {
            System.out.println(Thread.currentThread().getName()+"得到读锁，正在读取");
            Thread.sleep(500);
        } catch (InterruptedException e){
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放读锁");
            readLock.unlock();
        }
    }


    public static void write() {
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"得到写锁，正在写入");
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放写锁");
            writeLock.unlock();
        }
    }


    public static void main(String[] args) {
        new Thread(() -> read()).start();
        new Thread(() -> read()).start();
        new Thread(() -> write()).start();
        new Thread(() -> write()).start();

//        Thread-0得到读锁，正在读取
//        Thread-1得到读锁，正在读取
//        Thread-1释放读锁
//        Thread-0释放读锁
//        Thread-2得到写锁，正在写入
//        Thread-2释放写锁
//        Thread-3得到写锁，正在写入
//        Thread-3释放写锁

    }

}
